package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketAdExample;
import com.cskaoyan.market.db.mapper.MarketAdMapper;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MarketAdServiceImpl implements MarketAdService {
    @Autowired
    MarketAdMapper marketAdMapper;

    @Override
    public List<MarketAd> list(int page, int limit, String sort, String order, String name, String content) {
        MarketAdExample marketAdExample = new MarketAdExample();
        //设置查询结果的排序方式。sort和order是两个变量，通过拼接生成排序语句。
        marketAdExample.setOrderByClause(sort + " " + order);
        //创建一个MarketAdExample.Criteria对象，用于设置查询条件。
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        //模糊查询
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(content)) {
            criteria.andContentLike("%" + content + "%");
        }
        //分页插件
        PageHelper.startPage(page, limit);
        List<MarketAd> marketAdList =
                marketAdMapper.selectByExampleSelective(marketAdExample, MarketAd.Column.id, MarketAd.Column.name,
                        MarketAd.Column.link, MarketAd.Column.url, MarketAd.Column.position, MarketAd.Column.content,
                        MarketAd.Column.enabled, MarketAd.Column.addTime, MarketAd.Column.updateTime, MarketAd.Column.deleted);
        return marketAdList;
    }

    @Override
    public int create(MarketAd marketAd) {
        int flag = marketAdMapper.insertSelective(marketAd);
        return flag;
    }

    @Override
    public int  update(MarketAd marketAd) {
        MarketAdExample marketAdExample = new MarketAdExample();
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        criteria.andIdEqualTo(marketAd.getId());
        int flag = marketAdMapper.updateByExample(marketAd, marketAdExample);
        return flag;
    }

    @Override
    public int  delete(Integer id) {
        MarketAdExample marketAdExample = new MarketAdExample();
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        criteria.andIdEqualTo(id);
        int flag = marketAdMapper.deleteByExample(marketAdExample);
        return flag;
    }
}
